﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Hardware
{
    class Utils
    {

        /// <summary>
        /// 字节数组转16进制字符串：空格分隔
        /// </summary>
        /// <param name="byteDatas"></param>
        /// <returns></returns>
        public static string ByteArr2HexString(byte[] byteDatas)
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < byteDatas.Length; i++)
            {
                builder.Append(string.Format("{0:X2} ", byteDatas[i]));
            }
            return builder.ToString().Trim();
        }

        public static string Byte2HexString(byte _byte)
        {
            //string result = Convert.ToString(_byte, 16); // a
            return  _byte.ToString("X2");   //0A 或小写 .ToString("x2") 变成0a 
        }

        public static string String2HexString(string plainString, Encoding encode)
        {
            return BitConverter.ToString(encode.GetBytes(plainString)).Replace("-", " ");
        }

        /// <summary>
        /// 用指定编码将给定的字符串转16进制格式字符串
        /// </summary>
        /// <param name="plainString">待转换的字符串</param>
        /// <param name="encode">编码规则</param>
        /// 用法： string test= "%01#abcABCR00051**\r\n".ToHexString(Encoding.ASCII);
        /// 结果：25 30 31 23 61 62 63 41 42 43 52 30 30 30 35 31 2A 2A 0D 0A
        /// <returns></returns>
        public static string StringToHexString(string plainString, Encoding encode)
        {
            byte[] byteDatas = encode.GetBytes(plainString);
            return ByteArr2HexString(byteDatas);
        }

        /// <summary>
        /// 16进制格式字符串转字节数组
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static byte[] HexString2ByteArr(string hexString)
        {
            //以 ' ' 分割字符串，并去掉空字符
            string[] chars = hexString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            byte[] returnBytes = new byte[chars.Length];
            //逐个字符变为16进制字节数据
            for (int i = 0; i < chars.Length; i++)
            {
                returnBytes[i] = Convert.ToByte(chars[i], 16);
            }
            return returnBytes;
        }

        /// <summary>
        /// 16进制格式字符串转普通文本
        /// </summary>
        /// <param name="hexString">16进制格式字符串</param>
        /// <param name="encode">编码规则</param>
        /// <returns></returns>
        public static string HexString2AscIIString(string hexString, Encoding encode)
        {
            byte[] _bytes = HexString2ByteArr(hexString);
            return encode.GetString(_bytes);
        }

        public static bool IsValidIP(string strIP)
        {
            // 先检查有无非数字字符
            if (!Regex.IsMatch(strIP, "^[0-9.]+$"))
            {
                return false;
            }
            // 再检查数据范围是否合理
            string[] strNumArray = strIP.Split('.');
            if (strNumArray.Length != 4)
            {
                return false;
            }
            int n = 0;
            for (int i = 0; i < 4; ++i)
            {
                n = int.Parse(strNumArray[i]);
                if (n > 255)
                {
                    return false;
                }
            }
            return true;
        }

        public static bool IsHexCharacter(string str)
        {
            return Regex.IsMatch(str, "^[0-9A-Fa-f]+$");
        }

        // 大小端转换        
        public static UInt16 ReverseByte(UInt16 value)
        {
            return (UInt16)((value & 0xFFU) << 8 | (value & 0xFF00U) >> 8);
        }

        public static bool IsDecNumber(string str)
        {
            return Regex.IsMatch(str, "^[0-9]+$");
        }               

        public static double MeterUnitChange(double _weight, string meter_unit, string system_display_unit )
        {
            //单位相同时，直接返回
            if (meter_unit == system_display_unit)
            {
                return _weight;
            }
            switch (meter_unit)
            {
                case "公斤":
                case "KG":
                    switch (system_display_unit)
                    {
                        case "吨":
                        case "T":
                            return Math.Round(_weight / 1000, 3);
                        case "公斤":
                        case "KG":
                            return _weight;
                    }
                    break;
                case "吨":
                case "T":
                    switch (system_display_unit)
                    {
                        case "吨":
                        case "T":
                            return _weight;
                        case "公斤":
                        case "KG":                            
                            return Math.Round(_weight * 1000, 3);
                    }
                    break;
            }
            return 0;
        }

        public static byte[] AddBytes(byte[] data1, byte[] data2)
        {
            try
            {
                if (data1 == null)
                {
                    if (data2 == null)
                    {
                        return null;
                    }
                    else
                    {
                        return data2;
                    }
                }
                if (data2 == null)
                {
                    return data1;
                }
                byte[] data3 = new byte[data1.Length + data2.Length];
                data1.CopyTo(data3, 0);
                data2.CopyTo(data3, data1.Length);
                return data3;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 合并两个字节数组
        /// </summary>
        public static byte[] AddBytesTwo(byte[] a, byte[] b)
        {
            if (a == null) return b;
            if (b == null) return a;

            byte[] result = new byte[a.Length + b.Length];
            Buffer.BlockCopy(a, 0, result, 0, a.Length);
            Buffer.BlockCopy(b, 0, result, a.Length, b.Length);
            return result;
        }

        public static byte[] GetData(byte[] me, int idx = 0, int len = -1)
        {
            try
            {
                if (me == null) return null;
                if (len < 0) len = me.Length - idx;
                if ((idx + len) > me.Length) len -= ((idx + len) - me.Length);
                var buf = new byte[len];
                Array.Copy(me, idx, buf, 0, len);
                return buf;
            }
            catch (Exception ex)
            {
                return null;
            }
        }



    }
}
